//
//  CJExten+UIView.swift
//  CJCore
//
//  Created by 陈警卫 on 2024-07-05.
//

import UIKit
import Foundation

public extension UIView {
    
    /// 设置frame
    @objc func cj_frame(_ frame: CGRect) -> Self {
        self.frame = frame
        return self
    }
    
    /// 添加阴影
    @discardableResult
    @objc func cj_shadow(color: UIColor = .black,
                      offset: CGSize = CGSize(width: 2, height: 2),
                      opacity: Float = 0.5,
                      radius: CGFloat = 2) -> Self {
        self.layer.shadowColor = color.cgColor
        self.layer.shadowOffset = offset
        self.layer.shadowOpacity = opacity
        self.layer.shadowRadius = radius
        return self
    }
    
    /// 添加圆角
    @discardableResult
    @objc func cj_corner(conrners: UIRectCorner, radius: CGFloat = 5) -> CAShapeLayer {
        self.layoutIfNeeded()
        
        let maskPath = UIBezierPath(roundedRect: self.bounds,
                                    byRoundingCorners: conrners,
                                    cornerRadii: CGSize(width: radius, height: radius))
        let maskLayer = CAShapeLayer()
        maskLayer.path = maskPath.cgPath
        maskLayer.frame = self.bounds
        self.layer.mask = maskLayer
        return maskLayer
    }
    
    /// 添加阴影同时有圆角
    @discardableResult
    @objc func cj_shadowCorner(conrners: UIRectCorner,
                         radius: CGFloat = 5,
                         shadowColor: UIColor,
                         shadowOffset: CGSize,
                         shadowOpacity: Float,
                         shadowRadius: CGFloat = 2) -> CALayer {
        
        self.layoutIfNeeded()
        
        let maskPath = UIBezierPath(roundedRect: self.bounds, 
                                    byRoundingCorners: conrners,
                                    cornerRadii: CGSize(width: radius, height: radius))
        let maskLayer = CAShapeLayer()
        maskLayer.path = maskPath.cgPath
        maskLayer.bounds = self.bounds
        self.layer.mask = maskLayer
        
        let shadowLayer = CALayer()
        shadowLayer.frame = self.frame
        shadowLayer.cornerRadius = shadowRadius
        shadowLayer.masksToBounds = false
        
        shadowLayer.shadowColor = shadowColor.cgColor
        shadowLayer.shadowOffset = shadowOffset
        shadowLayer.shadowRadius = shadowRadius
        shadowLayer.shadowOpacity = shadowOpacity
        
        self.superview?.layer.insertSublayer(shadowLayer, below: self.layer)
        return shadowLayer
    }
    
    /// 添加边线
    @discardableResult
    @objc func cj_borderLine(x: CGFloat, y: CGFloat, width: CGFloat, height: CGFloat, color: UIColor) -> CALayer {
        let border = CALayer()
        border.backgroundColor = color.cgColor
        border.frame = CGRect(x: x, y: y, width: width, height: height)
        self.layer.addSublayer(border)
        return border
    }
    
    /// 添加渐变色
    @discardableResult
    func cj_gradientColor(colors: [UIColor], locations: [NSNumber]?, startPoint: CGPoint, endPoint: CGPoint) -> CAGradientLayer {
        let cgcolors: [CGColor] = colors.map { $0.cgColor }
        let gradientLayer = CAGradientLayer().cj_gradientLayer(colors: cgcolors,
                                                               locations: locations,
                                                               startPoint: startPoint,
                                                               endPoint: endPoint)
        gradientLayer.frame = CGRect(x: 0, y: 0, width: self.cj_width, height: self.cj_height)
        self.layer.insertSublayer(gradientLayer, at: 0)
        return gradientLayer
    }
    
    /// 添加渐变色动画
    @discardableResult
    func cj_gradientColorAnimation(startColors: [UIColor],
                                   endColors: [UIColor],
                                   locations: [NSNumber]?,
                                   startPoint: CGPoint,
                                   endPoint: CGPoint,
                                   duration: CFTimeInterval = 1.0)  -> (CAGradientLayer, CABasicAnimation) {
        let gradientLayer = cj_gradientColor(colors: startColors, locations: locations, startPoint: startPoint, endPoint: endPoint)
        
        // 添加渐变动画
        let gradientColorAnimation = CABasicAnimation(keyPath: "colors")
        gradientColorAnimation.duration = duration
        gradientColorAnimation.fromValue = startColors
        gradientColorAnimation.toValue = endColors
        gradientColorAnimation.fillMode = CAMediaTimingFillMode.forwards
        // 动画结束后保持最终的效果
        gradientColorAnimation.isRemovedOnCompletion = false
        gradientLayer.add(gradientColorAnimation, forKey: "cj_gradientColorAnimation")
        
        return (gradientLayer, gradientColorAnimation)
    }
}

public extension UIView {
    
    /// 移除子视图
    @objc func cj_removeAllSubviews() {
        for view in self.subviews {
            view.removeFromSuperview()
        }
    }
    
    /// 获取当前view的AnyClass
    func cj_superKind<T: NSObject>(_ aClass:T.Type = NSObject.self) -> T? {
        for view in sequence(first: self, next: { $0?.superview }) {
            if let responder = view?.next {
                if responder.isKind(of: aClass.self) {
                    return responder as? T
                }
            }
        }
        return nil
    }
    
    /// 获取当前view的UIViewController
    @objc func cj_currentVC() -> UIViewController? {
        var responder = next
        while responder != nil {
            if responder is UIViewController {
                return responder as? UIViewController
            }
            responder = responder?.next
        }
        return nil
    }
    
    /// 获取当前view的UINavigationController
    @objc func cj_currentNC() -> UINavigationController? {
        let vc = cj_currentVC()
        let nc = vc?.navigationController
        return nc
    }
    
    /// view截图成image
    @objc func cj_image() -> UIImage? {
        let scale = UIScreen.main.scale
        UIGraphicsBeginImageContextWithOptions(self.frame.size, self.isOpaque, scale)
        if let context = UIGraphicsGetCurrentContext() {
            self.layer.render(in: context)
            let image = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
            return image
        } else {
            UIGraphicsEndImageContext()
            return nil
        }
    }
}

public extension UIView {
    
    /// 添加 UITapGestureRecognizer
    @discardableResult
    @objc func cj_tapGestureAction(closure: @escaping (UIGestureRecognizer) -> ()) -> UITapGestureRecognizer {
        self.isUserInteractionEnabled = true
        let tap = UITapGestureRecognizer()
        tap.cj_addAction(closure: closure)
        self.addGestureRecognizer(tap)
        return tap
    }
    
    /// 添加 UITapGestureRecognizer
    @discardableResult
    @objc func cj_longGestureAction(closure: @escaping (UIGestureRecognizer) -> ()) -> UILongPressGestureRecognizer {
        self.isUserInteractionEnabled = true
        let long = UILongPressGestureRecognizer()
        long.cj_addAction(closure: closure)
        self.addGestureRecognizer(long)
        return long
    }
}
